#include "memory/tlb.h"
#include "common.h"
#include <time.h>
#include <stdlib.h>

void init_tlb() {
    int i;
    for(i = 0; i < TLB_SIZE; ++ i) {
        tlb[i].valid = false;
    }
}

int read_tlb(lnaddr_t addr) {
    uint32_t tag = ( addr >> 12 ) & 0xfffff;
    int i;
    for(i = 0; i < TLB_SIZE; ++ i) {
        if( tlb[i].tag == tag && tlb[i].valid ) {
            break;
        }
    }
    return i;
}

void write_tlb(lnaddr_t lnaddr, hwaddr_t hwaddr) {
    uint32_t tag = ( lnaddr >> 12 ) & 0xfffff;
    uint32_t page = ( hwaddr >> 12 ) & 0xfffff;
    int i;
    for(i = 0; i < TLB_SIZE; ++ i) {
        if(!tlb[i].valid) {
            tlb[i].valid = true;
            tlb[i].tag = tag;
            tlb[i].page = page;
            break;
        }
    }
    /* TLB is full, randomly replace one */
    if(i == TLB_SIZE) {
        srand(time(0));
        i = rand() % TLB_SIZE;
        tlb[i].tag = tag;
        tlb[i].page = page;
        tlb[i].valid = true;
    }
}